package com.example.lib5.hashTab.test;

public class HashTabDemoD {
    public static void main(String[] args) {
        HashTabC hashTabC = new HashTabC(3);
        hashTabC.add(new RoleC(111,"唐三"));
        hashTabC.add(new RoleC(112,"小舞"));
        hashTabC.add(new RoleC(113,"千仞雪"));
        hashTabC.add(new RoleC(114,"千道流"));
        hashTabC.add(new RoleC(115,"千寻疾"));
        hashTabC.add(new RoleC(116,"比比东"));
        hashTabC.add(new RoleC(117,"胡列娜"));
        hashTabC.list();

    }
}

//哈数表
class HashTabC {

    private int size;
    LinkListRoleC[] linkListRoleCS;

    public HashTabC(int size) {
        this.size=size;
        linkListRoleCS=new LinkListRoleC[size];
        for (int i = 0; i < linkListRoleCS.length; i++) {
            linkListRoleCS[i]=new LinkListRoleC();
        }
    }

    public void add(RoleC roleC) {
        linkListRoleCS[hashFunction(roleC.id)].add(roleC);
    }
    //散列函数
    private int hashFunction(int id) {
        return id%size;
    }

    public void list() {
        for (int i = 0; i < linkListRoleCS.length; i++) {
            linkListRoleCS[i].list(i);
        }
    }
}
//链表
class LinkListRoleC{
    RoleC head;
    public void add(RoleC roleC) {
        //判断链表是否为空
        if (head==null) {
            head=roleC;
            return;
        }
        RoleC temp=head;
        //不为空，获取链表的最后一个，然后加入
        while (true) {
            if (temp.next==null) {
                break;
            }
            temp=temp.next;
        }
        temp.next=roleC;
    }

    public void list(int i) {
        //判断链表是否为空
        if (head==null) {
            System.out.println("链表"+i+"为空，无法打印");
            return;
        }
        //不为空，辅助指针，遍历链表进行打印
        RoleC temp=head;
        System.out.println("链表"+i+"打印为：");
        while (true) {
            System.out.println(temp.toString());
            if (temp.next==null) {
                break;
            }
            temp=temp.next;
        }

    }
}

//节点
class RoleC{

    int id;
    String name;
    RoleC next;

    public RoleC(int id, String name) {
        this.id=id;
        this.name=name;
    }

    @Override
    public String toString() {
        return "RoleC{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
